package org.artifact.core.context.packet;

import lombok.Data;
import org.artifact.core.context.bytebuf.IByteBuff;
import org.artifact.core.lang.ISerializable;

import java.util.HashMap;
import java.util.Map;

@Data
public class NetworkPacket implements ISerializable<NetworkPacket> {
    /**
     * 包头
     */
    private Map head = new HashMap<>();
    /**
     * 包体
     */
    private Map body = new HashMap<>();

    @Override
    public IByteBuff toByteBuff(IByteBuff buff) {
        buff.writeMap(head);
        buff.writeMap(body);
        return buff;
    }

    @Override
    public NetworkPacket forByteBuff(IByteBuff buff) {
        this.head = buff.readMap();
        this.body = buff.readMap();
        return this;
    }

    public <T> T getHeader(Object key) {
        return (T) head.get(key);
    }

    public <T> T getHeader(Object key,T defaultValue) {
        return (T) head.getOrDefault(key,defaultValue);
    }

    public void setHeader(Object key, Object val) {
        head.put(key, val);
    }

	@Override
	public String toString() {
		return "NetworkPacket [head=" + head + ", body=" + body + "]";
	}
}
